package com.dayuanit.atm.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.dayuanit.atm.dao.DetailDao;
import com.dayuanit.atm.domain.Detail;
import com.dayuanit.atm.util.DataBaseUtils;

public class DetailDaoImpl implements DetailDao {
	
	private static Connection conn = DataBaseUtils.getConn();

	@Override
	public int addDetail(Detail detail) {
		PreparedStatement pst = null;
		int rows = -1;
		try {
			String sql = "insert into atm_detail(card_num, amount, opt_type, create_time, tips) "
					+ "value(?, ?, ?, now(), ?);";
			
			pst = conn.prepareStatement(sql);
			
			pst.setString(1, detail.getCardNum());
			pst.setInt(2, detail.getAmount());
			pst.setInt(3, detail.getOptType());
			pst.setString(4, detail.getTips());
			
			rows = pst.executeUpdate();
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != pst) {
					pst.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return rows;
	}

	@Override
	public List<Detail> listDetail(String cardNum) {
		String sql = "select id, card_num, amount, opt_type, create_time, tips from atm_detail where card_num=? order by create_time asc;";
		List<Detail> detailList = new ArrayList<Detail>();
		
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, cardNum);
			
			rs = pst.executeQuery();
			while (rs.next()) {
				
				int id = rs.getInt("id");
				String bankCardNum = rs.getNString("card_num");
				int amount = rs.getInt("amount");
				int optType = rs.getInt("opt_type");
				java.sql.Timestamp createTime = rs.getTimestamp("create_time");
				String tips = rs.getNString("tips");
				
				Detail detail = new Detail();
				detail.setAmount(amount);
				detail.setCardNum(bankCardNum);
				detail.setCreateTime(new Date(createTime.getTime()));
				detail.setId(id);
				detail.setOptType(optType);
				detail.setTips(tips);
				
				detailList.add(detail);
			}
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != rs) {
					rs.close();
				}
				
				if (null != pst) {
					pst.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return detailList;
	}

}
